//
//  TVCOfDetailVideo.m
//  To Feel
//
//  Created by 曹宇 on 16/7/14.
//  Copyright © 2016年 caoyu. All rights reserved.
//

#import "TVCOfDetailVideo.h"
#import "CellOfTVCDetailVideo.h"
#import "NetworkingHandler.h"
#import "ModelOfSecondTVC.h"
#import "DetailViewOfTVCToPlay.h"
#import "Masonry.h"
#import "MJRefresh.h"
#import "CYPlayerView.h"
#import "UIImageView+WebCache.h"
#import "SDWebImageManager.h"
#import "VCOfPlay.h"
#import "SJ_360Player.h"
@interface TVCOfDetailVideo ()
@property(nonatomic, retain) NSMutableArray *arrOfData;
@property(nonatomic, retain) NSMutableArray *arrOfModel;// 存model
@property(nonatomic, retain) NSString *httpUrl;
@property(nonatomic, retain) DetailViewOfTVCToPlay *detailViewOfTVC;
@property(nonatomic, retain) UIActivityIndicatorView *activityIndicator;
@property(nonatomic, assign) NSInteger number;
//@property(nonatomic, copy) NSString *strOfNextID;
//@property(nonatomic, copy) NSString *strOfNextTitle;


@end

@implementation TVCOfDetailVideo

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatActivityIndicator];
    [self configTableView];
    [self handleData];
    [self creatFooter];
}



- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    [self.activityIndicator stopAnimating];
    
}

- (void)creatActivityIndicator {
    self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [self.tableView addSubview:self.activityIndicator];
    
    [self.activityIndicator mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.tableView);
        make.centerY.equalTo(self.tableView);
    }];
    
    [self.activityIndicator startAnimating];
    
}

- (void)handleData {
    
    self.arrOfData = [NSMutableArray array];
    self.arrOfModel = [NSMutableArray array];
    
    if ([self.idOfUrl isEqualToString:@"0"]) {
        _httpUrl = @"http://baobab.wandoujia.com/api/v3/specialTopics?_s=42a53b006b9acec3952aa0362dbf3825&f=iphone&net=wifi&num=20&u=b3dd1f64e4b4e6660ab603a76e310e3e117917af&v=2.2.0&vc=721";
    } else if ([_idOfUrl isEqualToString:@"1"]) {
        _httpUrl = @"http://baobab.wandoujia.com/api/v3/tag/videos?_s=fe62ed7e3089f0636e5cce3c420c8cde&f=iphone&net=wifi&num=20&start=0&strategy=date&tagId=658&u=b3dd1f64e4b4e6660ab603a76e310e3e117917af&v=2.2.0&vc=721";
    } else {
        _httpUrl= [NSString stringWithFormat:@"http://baobab.wandoujia.com/api/v3/videos?categoryId=%@", self.idOfUrl];
    }
    
    NetworkingHandler *nt = [[NetworkingHandler alloc] init];
    [nt netWorkingHandlerGETWithURL:_httpUrl completion:^(id result, NSData *data, NSURLResponse *response, NSError *error) {
        self.arrOfData = [result objectForKey:@"itemList"];
        for (NSDictionary *dic in self.arrOfData) {
            
            ModelOfSecondTVC *model = [[ModelOfSecondTVC alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.arrOfModel addObject:model];
            
            
        }
        
    }];
    [self.tableView reloadData];


    
    
}

- (void)creatFooter {
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _number+=20;
        [self loadData];
    }];
    
    if (![_httpUrl isEqualToString:@"0"]) {
        if (![_httpUrl isEqualToString:@"1"]) {
            [self.tableView.mj_footer beginRefreshing];
        }
    }
}

- (void)loadData {
    
    
    _httpUrl= [NSString stringWithFormat:@"http://baobab.wandoujia.com/api/v3/videos?start=%ld&num=20&categoryId=%@", _number, self.idOfUrl];
    
    NetworkingHandler *nt = [[NetworkingHandler alloc] init];
    [nt netWorkingHandlerGETWithURL:_httpUrl completion:^(id result, NSData *data, NSURLResponse *response, NSError *error) {
        self.arrOfData = [result objectForKey:@"itemList"];
        
        for (NSDictionary *dic in self.arrOfData) {
            
            ModelOfSecondTVC *model = [[ModelOfSecondTVC alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.arrOfModel addObject:model];
            
            
        }
       
       
    }];

    [self.tableView reloadData];
    [self.tableView.mj_footer endRefreshing];
}

- (void)configTableView {
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[CellOfTVCDetailVideo class] forCellReuseIdentifier:@"CellOfTVCDetailVideo"];
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _arrOfModel.count;
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CellOfTVCDetailVideo *cell = [tableView dequeueReusableCellWithIdentifier:@"CellOfTVCDetailVideo" forIndexPath:indexPath];
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    
    [cell.viewOfImg addGestureRecognizer:longPress];
    
    cell.model = [_arrOfModel objectAtIndex:indexPath.row];
    
    return cell;
}

- (void)longPress:(UILongPressGestureRecognizer *)longPress {
    
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:[longPress locationInView:self.tableView]];
    
    CellOfTVCDetailVideo *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    
    switch (longPress.state) {
            
        case UIGestureRecognizerStateBegan:
            cell.labelOfTitle.alpha = 0;
            cell.labelOfInfo.alpha = 0;
            cell.viewOfImg.alpha = 0;
            break;
        case UIGestureRecognizerStateChanged:
            cell.labelOfTitle.alpha = 1;
            cell.labelOfInfo.alpha = 1;
            cell.viewOfImg.alpha = 0.2;
        case UIGestureRecognizerStateEnded:
            cell.labelOfTitle.alpha = 1;
            cell.labelOfInfo.alpha = 1;
            cell.viewOfImg.alpha = 0.2;
        case UIGestureRecognizerStateCancelled:
            cell.labelOfTitle.alpha = 1;
            cell.labelOfInfo.alpha = 1;
            cell.viewOfImg.alpha = 0.2;
        default:
            break;
    }
}
#pragma mark - tableView Delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return  SCREEN_HEIGHT / 3 + 10;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    ModelOfSecondTVC *model = [_arrOfModel objectAtIndex:indexPath.row];
    

    
//    ModelOfSecondTVC *modelOfNext = [_arrOfModel objectAtIndex:indexPath.row + 1];
//    self.strOfNextID = [modelOfNext.data objectForKey:@"id"];
//    self.strOfNextTitle = [modelOfNext.data objectForKey:@"title"];
//    
    
    CellOfTVCDetailVideo *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    CGRect rectInTableView = [tableView rectForRowAtIndexPath:indexPath];
    
    CGRect rect = [tableView convertRect:rectInTableView toView:nil];
    
    CGFloat y = rect.origin.y;
    
    self.detailViewOfTVC = [[DetailViewOfTVCToPlay alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) model:model];
    
    self.detailViewOfTVC.imgOfTop.image = cell.imgOfPlay.image;
    
    self.detailViewOfTVC.offSetY = y;
    
    [[self.tableView superview] addSubview:self.detailViewOfTVC];
    
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeAction:)];
    
    self.detailViewOfTVC.imgOfBottom.userInteractionEnabled = YES;
    
    swipe.direction = UISwipeGestureRecognizerDirectionUp;
    
    [self.detailViewOfTVC.imgOfBottom addGestureRecognizer:swipe];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionOfImage:)];
    
    self.detailViewOfTVC.imgOfTop.userInteractionEnabled = YES;
    
    [self.detailViewOfTVC.imgOfTop addGestureRecognizer:tap];
    
    [self.detailViewOfTVC animationShow];
    
    
    
    
}

- (void)swipeAction:(UISwipeGestureRecognizer *)swipe {
    
    [self.detailViewOfTVC animationDissmis];
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
    
}

- (void)tapActionOfImage:(UITapGestureRecognizer *)tap {
    
    VCOfPlay *playerOfNormal = [[VCOfPlay alloc]init];
    playerOfNormal.URlOfVideo = [self.detailViewOfTVC.modelOfData.data objectForKey:@"playUrl"];
    playerOfNormal.titleOfVideo = [self.detailViewOfTVC.modelOfData.data objectForKey:@"title"];
  NSArray *arrOfPlayInfo = [NSArray arrayWithArray:[self.detailViewOfTVC.modelOfData.data objectForKey:@"playInfo"]];
   playerOfNormal.playInfoURLOfNormal = [arrOfPlayInfo[0] objectForKey:@"url"];
    
//    playerOfNormal.strOfNextID = self.strOfNextID;
//    playerOfNormal.strOfNexttitle = self.strOfNextTitle;
//    
//    
    
    if (arrOfPlayInfo.count == 2) {
        
        playerOfNormal.playInfoURLOfHigh = [arrOfPlayInfo[1] objectForKey:@"url"];
    }
    
    if ([[self.detailViewOfTVC.modelOfData.data objectForKey:@"type"] isEqualToString:@"PANORAMIC"]) {
        Sj_360Player *playerOf360 = [[Sj_360Player alloc]initWithNibName:nil bundle:nil url:[NSURL URLWithString:[self.detailViewOfTVC.modelOfData.data objectForKey:@"playUrl"]]];
        [self presentViewController:playerOf360 animated:YES completion:nil];
      
    }else{
      
        [self presentViewController:playerOfNormal animated:YES completion:nil];
    }
    
}

#pragma mark - 添加每个cell出现时的3D动画
-(void)tableView:(UITableView *)tableView willDisplayCell:(CellOfTVCDetailVideo *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{


    ModelOfSecondTVC *model = self.arrOfModel[indexPath.row];
//    SDWebImageManager *manager = [SDWebImageManager sharedManager];
//    if (![manager cachedImageExistsForURL:[NSURL URLWithString:[model.data objectForKey:@"image"]]]) {


    
        CATransform3D rotation;//3D旋转

        rotation = CATransform3DMakeTranslation(0 ,50 ,20);
        //逆时针旋转
//      rotation = CATransform3DMakeRotation( M_PI_4 , 0.0, 0.7, 0.4);

        rotation = CATransform3DScale(rotation, 0.9, .9, 1);

        rotation.m34 = 1.0/ -600;

        cell.layer.shadowColor = [[UIColor blackColor]CGColor];
        cell.layer.shadowOffset = CGSizeMake(10, 10);
        cell.alpha = 0;

        cell.layer.transform = rotation;

        [UIView beginAnimations:@"rotation" context:NULL];
        //旋转时间
        [UIView setAnimationDuration:0.6];
        cell.layer.transform = CATransform3DIdentity;
        cell.alpha = 1;
        cell.layer.shadowOffset = CGSizeMake(0, 0);
        [UIView commitAnimations];
//    }


    [cell cellOffset];
    cell.model = model;
}


@end
